package com.th.controller;

import com.github.pagehelper.PageInfo;
import com.th.pojo.ProductInfo;
import com.th.pojo.vo.ProductInfoVo;
import com.th.service.ProduceInfoService;
import com.th.service.impl.ProduceInfoServiceImpl;
import com.th.utils.FileNameUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author ThreePure
 * @date 2022/3/27 16:30
 * @description: TODO
 * @since 1.8
 */
@Controller
@RequestMapping("/prod")
public class ProductInfoAction {

    /**每页显示的记录数*/
    public static final int PAGE_SIZE = 5;

    /**异步上传文件名称*/
    String saveFileName = "";

    /**所有的界面层，一定有业务逻辑层的对象*/
    @Autowired
    ProduceInfoService produceInfoService;

    /**
     * @description:  显示全部商品信息
     * @date 2022/3/27 17:16
     * @Param: [request]
     * @Return: java.lang.String
     */
    @RequestMapping("/getAll")
    public String getAll(HttpServletRequest request){
        List<ProductInfo> list = produceInfoService.getAll();
        request.setAttribute("list", list);
        return "product";
    }

    /**
     * @description:  分页显示第一页
     * @date 2022/3/27 17:46
     * @Param: [request]
     * @Return: java.lang.String
     */
    @RequestMapping("/split")
    public String splitOne(HttpServletRequest request){
        PageInfo info = null;
        Object ov = request.getSession().getAttribute("prodVo");
        if (ov != null){
            info  = produceInfoService.splitPageVo((ProductInfoVo) ov, PAGE_SIZE);
            request.getSession().removeAttribute("prodVo");
        }else {
            //得到第一页数据
            info = produceInfoService.splitPage(1, PAGE_SIZE);
        }
        request.setAttribute("info", info);
        return "product";
    }

    /**
     * @description:  分页显示当前页
     * @date 2022/3/27 18:35
     * @Param: [page, session]
     * @Return: void
     */
    /*@ResponseBody
    @RequestMapping("/ajaxsplit")
    public void ajaxSplit(int page, HttpSession session){
        //获取当前page参数的页面的数据
        PageInfo info = produceInfoService.splitPage(page, PAGE_SIZE);
        session.setAttribute("info", info);
    }*/

    /**
     * @description:  分页显示当前页
     * @date 2022/3/27 18:35
     * @Param: [page, session]
     * @Return: void
     */
    @ResponseBody
    @RequestMapping("/ajaxsplit")
    public void ajaxSplit(ProductInfoVo vo, HttpSession session){
        //获取当前page参数的页面的数据
        PageInfo info = produceInfoService.splitPageVo(vo, PAGE_SIZE);
        session.setAttribute("info", info);
    }

    /**
     * @description:  多条件查询功能实现
     * @date 2022/3/28 15:08
     * @Param: [vo, session]
     * @Return: void
     */
    @ResponseBody
    @RequestMapping("/condition")
    public void condition(ProductInfoVo vo, HttpSession session){
        System.out.println("【VO】"+vo.toString());
        List<ProductInfo> list = produceInfoService.selectCondition(vo);
        session.setAttribute("list", list);
    }

    /**
     * @description:  商品图片异步上传
     * @date 2022/3/27 20:54
     * @Param: [pimage, request]
     * @Return: java.lang.Object
     */
    @ResponseBody
    @RequestMapping("/ajaxImg")
    public Object ajaxImg(MultipartFile pimage, HttpServletRequest request){
        //提取生成文件名，UUID + 上传图片的后缀
        saveFileName = FileNameUtil.getUUIDFileName()+FileNameUtil.getFileType(pimage.getOriginalFilename());
        //得到项目中图片存储路径
        String path = request.getServletContext().getRealPath("/image_big");

        //转存
        try {
            pimage.transferTo(new File(path + File.separator + saveFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回客户端Json对象，封装图片路径，为了在页面中实现立即回显
        JSONObject object = new JSONObject();
        object.put("imgurl", saveFileName);
        return object.toString();
    }

    /**
     * @description:  上架商品
     * @date 2022/3/27 21:22
     * @Param: [info, request]
     * @Return: java.lang.String
     */

    @RequestMapping("/save")
    public String save(ProductInfo info, HttpServletRequest request){
        info.setpImage(saveFileName);
        info.setpDate(new Date());
        //info对象中有表单提交的5个数据，以及异步上传的图片名称和上架时间
        int num = -1;
        try {
            num = produceInfoService.save(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0){
            request.setAttribute("msg", "上架成功！");
        }else {
            request.setAttribute("msg", "上架失败！");
        }
        //清空saveFileName,方便下次新增和更新
        saveFileName = "";
        return "forward:/prod/split.action";
    }

    /**
     * @description:  获取某个商品的信息，并给前端回显
     * @date 2022/3/27 21:45
     * @Param: [pid, model]
     * @Return: java.lang.String
     */
    @RequestMapping("/one")
    public String one(int pid, ProductInfoVo vo, Model model,HttpSession session){
        ProductInfo info = produceInfoService.getById(pid);
        model.addAttribute("prod", info);
        //将多条件以及页码放入session中，更新操作后时读取条件和页码进行处理
        session.setAttribute("prodVo", vo);
        return "update";
    }

    /**
     * @description:  更新商品
     * @date 2022/3/27 22:24
     * @Param: [info, request]
     * @Return: java.lang.String
     */
    @RequestMapping("/update")
    public String update(ProductInfo info, HttpServletRequest request){
        //因为ajax的异步上传图片，如果有上传过，则saveFileName存有图片名称，如果没有异步上传过，则saveFileName为空
        if (!saveFileName.equals("")){
            //异步上传过图片
            info.setpImage(saveFileName);
        }
        //完成更新操作
        int num = -1;
        try {
            num = produceInfoService.update(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0){
            //更新成功
            request.setAttribute("msg", "更新成功！");
        }else {
            request.setAttribute("msg", "更新失败！");
        }
        //清空saveFileName，保证下次使用这个变量的准确性
        saveFileName= "";
        return "forward:/prod/split.action";
    }

    /**
     * @description:  删除单个商品
     * @date 2022/3/27 22:29
     * @Param: [pid, request]
     * @Return: java.lang.String
     */
    @RequestMapping("delete")
    public String delete(int pid, ProductInfoVo vo, HttpServletRequest request){
        int num = -1;
        try {
            num = produceInfoService.delete(pid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0) {
            request.setAttribute("msg", "删除成功");
            request.getSession().setAttribute("deleteProdVo", vo);
        }else {
            request.setAttribute("msg", "删除失败");
        }
        //不能使用”/split“ 控制器，因为删除后并没有刷新整个product.jsp页面，无法使用该页面中开始位置的msg弹窗提醒删除结果弹窗，故重写"/deleteAjaxSplit"
        return "forward:/prod/deleteAjaxSplit.action";
    }

    /**
     * @description:  分页显示第一页，用于删除商品后刷新
     * @date 2022/3/27 23:51
     * @Param: [request]
     * @Return: java.lang.Object
     */
    @ResponseBody
    @RequestMapping(value = "/deleteAjaxSplit", produces = "text/html;charset=UTF-8")
    public Object deleteAjaxSplit(HttpServletRequest request){
        PageInfo info = null;
        Object vo = request.getSession().getAttribute("deleteProdVo");
        if (vo != null){
            info = produceInfoService.splitPageVo((ProductInfoVo) vo, PAGE_SIZE);
        }else {
            //取得第一页的数据
            info = produceInfoService.splitPage(1, PAGE_SIZE);
        }
        request.getSession().setAttribute("info", info);
        return request.getAttribute("msg");
    }

    /**
     * @description:  批量删除
     * @date 2022/3/28 11:28
     * @Param: [pids, request]
     * @Return: java.lang.String
     */
    @RequestMapping("/deleteBatch")
    public String deleteBatch(String pids, HttpServletRequest request){
        //将上传的字符串按照","截开，得到商品id的字符数组
        String[] ps = pids.split(",");

        try {
            int num = produceInfoService.deleteBatch(ps);
            if (num > 0){
                request.setAttribute("msg", "批量删除成功");
            }else {
                request.setAttribute("msg", "批量删除失败");
            }
        } catch (Exception e) {
            request.setAttribute("msg", "商品不可删除");
        }
        return "forward:/prod/deleteAjaxSplit.action";
    }





}
